﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net;
using DataLayer;
using System.Text.RegularExpressions;

/// <summary>
/// Summary description for Functions
/// </summary>
public static class Functions
{
   public static string GetUserID(string UserName)
   {
      LdapUser UserInfo = new LdapUser(UserName);
      return UserInfo.UserID;
   }
   public static UserType GetUserType(string UserName)
   {
      LdapUser UserInfo = new LdapUser(UserName);
      return UserInfo.UserLdapType;
   }
   private static Regex _StripTagEx = new Regex("</?[^>]+>", RegexOptions.Compiled);
   public static string StripHtml(string val)
   {
      return _StripTagEx.Replace(val, string.Empty).Replace(Environment.NewLine, " ").Replace("\n", " ").Replace("\r", " ");
   }
   public static bool IPIsIntranet(string strIP)
   {
      try
      {
         IPHostEntry P = Dns.GetHostEntry(strIP);
         IPAddress IP = P.AddressList[0];
         
         byte[] IPSegments = IP.GetAddressBytes();
         if (IPSegments.Length == 4)
         {            
            if (
               (IPSegments[0] == 127 && IPSegments[1] == 0 && IPSegments[2]==0 && IPSegments[3] == 1) ||
               (IPSegments[0] == 137 && IPSegments[1] == 132)
               )
            {
               return true;
            }
         }
         return false;
      }
      catch
      {
         return false;
      }
   }

   public static Guid GetUserProviderKey()
   {
      string UserName = HttpContext.Current.User.Identity.Name;
      return GetUserProviderKey(UserName);
   }

   public static Guid GetUserProviderKey(string UserName)
   {
      Guid result = Guid.Empty;
      string Key = UserName + "_UserProviderKey";
      try
      {
         result = (Guid)HttpRuntime.Cache[Key];

         if (result != Guid.Empty)
            return result;

         throw new Exception();
      }
      catch
      {
      }

      MembershipUser Mbr = Membership.GetUser(UserName);
      result = new Guid(Mbr.ProviderUserKey.ToString());
      HttpRuntime.Cache.Add(Key, result, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(1, 0, 0), System.Web.Caching.CacheItemPriority.Normal, null);

      return result;
   }

   public static Guid GetRoleID(string RoleName)
   {
      using (var db = DatabaseHelper.GetDashboardData())
      {
         var rows = from p in db.aspnet_Roles
                    where p.LoweredRoleName == RoleName
                    select p.RoleId;
         if (rows.Count() > 0)
         {
            return rows.First();
         }
      }

      return Guid.Empty;
   }
}
